<template>
  <div>
    <my-header :data="headerData"/>
    <el-row>
      <el-card>
        <div slot="header">图片修改建议（点击图片进入涂鸦页面)</div>
        <div>
          <el-form label-width="200px">
            <el-form-item label="图片：">
              <el-image
                style="width: 400px; height: 100%"
                :src="url"
                @click.stop="handleShowCanvas"
                ></el-image>
                <a
                  href="javascript:void(0);"
                  ref="download"
                  download="picture.png"
                  v-show="false"
                ></a>
            </el-form-item  >
            <el-form-item label="修改建议：">
              <el-input style="width: 400px" v-model="masker" placeholder="请您反馈意见" @change="sumitMasker" type="textarea" :rows="3"></el-input>
            </el-form-item>
            <el-form-item>
              <!-- <el-tooltip class="item" effect="dark" content="在新页面打开后右键保存到本地" placement="top"> -->
                <el-button class="el_button" icon="el-icon-download" type="primary" @click="download">下载图片</el-button>
              <!-- </el-tooltip> -->
              <el-button class="el_button" type="primary" @click="sumit">提交修改</el-button>
              <el-button class="el_button" type="primary" @click="cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </el-row>
    <plant
      ref="plant"
      :show="show"
      :bg="bg"
      @close="cancelPlant"
      @save="savePlant"/>
  </div>
</template>
<script>
import Plant from './components/planter.vue'
import myHeader from '@/components/header/index.vue'
// 转换为Base64
export default {
  components: {
    'my-header': myHeader,
    'plant': Plant
  },
  data() {
    return {
      headerData: [
        {
          path: '/',
          value: '首页'
        },
        {
          path: '/user',
          value: '客户中心'
        },
        {
          path: '/user/edit',
          value: '编辑'
        }
      ],
      // 图片背景
      bg: '',
      // 涂鸦、图片地址
      url: '',
      // 下载图片地址
      downloadurl: '',
      // 备注信息数据
      maskerJSonData: [],
      // 涂鸦信息数据
      imgPlantData: [],
      // 图片索引
      photoIndex: '',
      // 图库id
      libraryId: '',
      // 图片id
      photoId: '',
      // 备注
      masker: '',
      // 涂鸦数据
      imgplant: '',
      // 编辑数据
      editData: {},
      // 画板内容
      // 是否显示
      show: false
      // 默认画笔颜色
    }
  },
  created() {
    // 获取地址数据
    var urlData = this.$route.query
    this.photoIndex = urlData.index
    this.libraryId = urlData.id
    this.photoId = urlData.picId
    // console.log(urlData, '====获取的数据')
    var time = setTimeout(() => {
      this.getBase64(window.sessionStorage.getItem('photoUrl'), callback => {
        // console.log(callback, '===bg')
        this.bg = callback
        // return bg
      })
      clearTimeout(time)
    }, 700)
    // 获取数据
    this.getData()
  },
  watch: {},
  methods: {
    // 显示绘图板
    handleShowCanvas() {
      this.show = true
      var time = setTimeout(() => {
        this.$refs.plant.handleClearCanvas()
        this.$refs.plant.handleChangeToolType(1)
        clearTimeout(time)
      }, 1000)
    },
    // 取消涂鸦
    cancelPlant() {
      this.show = false
    },
    // 保存涂鸦
    savePlant(val) {
      this.imgPlantData[this.photoIndex].id = this.editData.pics[this.photoIndex].pics_id
      var _this = this
      var i
      this.imgPlantData.forEach((e, index) => {
        var id = e.id.toString()
        // console.log(id, _this.photoId, index, '======fdsafsdafsd')
        if (id === _this.photoId.toString()) {
          i = index
        }
      })
      // console.log(i, '====fshuahus')
      this.imgPlantData[i].plantData = val
    },
    getBase64(imgUrl, callback) {
      // 一定要设置为let，不然图片不显示
      const image = new Image()
      // 解决跨域问题
      image.setAttribute('crossOrigin', 'anonymous')
      const imageUrl = imgUrl
      image.src = imageUrl
      // image.onload为异步加载
      // eslint-disable-next-line no-undef
      image.onload = function() {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        // eslint-disable-next-line no-undef
        context.drawImage(image, 0, 0, image.width, image.height)
        var quality = 0.8
        // 这里的dataurl就是base64类型
        // 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
        const dataurl = canvas.toDataURL('image/jpeg', quality)
        callback = callback ? callback(dataurl) : null // 调用回调函数
      }
    },
    // 图片下载
    download() {
      var _this = this
      var name
      this.$http.get(`goods/${this.libraryId}`).then(res => {
        // console.log(res.data.data)
        if (res.data.meta.status !== 200) return this.$message.error('获取图库名称失败,下载图片失败')
        name = res.data.data.goods_name + _this.photoId
        this.downloadIamge(this.downloadurl, name)
      })
    },
    // 封装图片下载函数
    downloadIamge (imgsrc, name) { // 下载图片地址和图片名
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
        var a = document.createElement('a') // 生成一个a元素
        var event = new MouseEvent('click') // 创建一个单击事件
        a.download = name // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = imgsrc
    },
    // 获取数据
    async getData() {
      // var _this = this
      this.downloadurl = window.sessionStorage.getItem('photoUrl')
      this.url = window.sessionStorage.getItem('photoUrl')
      this.maskerJSonData = JSON.parse(JSON.parse(window.sessionStorage.getItem('maskerJson')))
      this.imgPlantData = JSON.parse(JSON.parse(window.sessionStorage.getItem('PlantJson')))
      // console.log(this.imgPlantData, '====imgData')
      var i, j
      this.maskerJSonData.forEach((e, index) => {
        if (e.id.toString() === this.photoId.toString()) {
          i = index
        }
      })
      this.imgPlantData.forEach((e, index) => {
        if (e.id.toString() === this.photoId.toString()) {
          j = index
        }
      })
      this.masker = this.maskerJSonData[i].masker
      this.url = this.imgPlantData[j].plantData
      // console.log(this.url, '=======')
      if (this.url === '') {
        this.url = window.sessionStorage.getItem('photoUrl')
      }
      const { data: res } = await this.$http.get(`goods/${this.libraryId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editData = res.data
      console.log(this.editData, '======获取过来的数据')
    },
    // 取消按钮
    cancel() {
      window.sessionStorage.removeItem('photoUrl')
      window.sessionStorage.removeItem('maskerJson')
      window.sessionStorage.removeItem('PlantJson')
      this.$router.push(`/user/show?id=${this.editData.goods_id}&name=${this.editData.goods_name}`)
    },
    // 监听意见修改
    sumitMasker() {
      // this.maskerJSonData[this.photoIndex].masker = this.masker
      this.maskerJSonData[this.photoIndex].id = this.editData.pics[this.photoIndex].pics_id
      var _this = this
      var i
      this.maskerJSonData.forEach((e, index) => {
        // console.log(e.id.toString() === _this.photoId.toString(), index, '======fdsafsdafsd')
        if (e.id.toString() === _this.photoId.toString()) {
          i = index
        }
      })
      // console.log(i, '====fshuahus')
      this.maskerJSonData[i].masker = this.masker
      // this.editData.pics[this.photoIndex].pics_master = this.masker
    },
    // 提交意见
    async sumit() {
      this.editData.goods_big_logo = JSON.stringify(JSON.stringify(this.maskerJSonData))
      this.editData.goods_small_logo = JSON.stringify(JSON.stringify(this.imgPlantData))
      // this.editData.goods_weight = this.editData.pics.length
      console.log(this.editData, '=====修改后的数据')
      const { data } = await this.$http.put(`goods/${this.editData.goods_id}`, this.editData)
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      window.sessionStorage.removeItem('photoUrl')
      window.sessionStorage.removeItem('maskerJson')
      window.sessionStorage.removeItem('PlantJson')
      this.$message.success('意见提交成功')
      this.$router.push(`/user/show?id=${this.editData.goods_id}&name=${this.editData.goods_name}`)
    }
  }
}

</script>
<style lang="less" scoped>
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
/deep/.el-dialog {
  display: flex;
  flex-direction: column;
  align-items: center;
  & > div {
    width: 100%;
    box-sizing: border-box;
  }
  .el-dialog__header {
    padding: 0 20px;
    p {
      padding: 20px 0;
      border-bottom: 1px solid #bdbdbd;
    }
  }
  .el-dialog__body {
    padding: 10px 20px;
    flex: 1;
    height: 0;
    padding-top: 0;
    position: relative;
    overflow: hidden;
    .d_body {
      height: 100%;
      overflow-y: auto;
      padding-top: 50px;
      .board {
        position: relative;
        min-height: 100%;
        canvas {
          // width: 100%;
          position: absolute;
          margin: 0 auto;
          left: 0;
          right: 0;
          top: 0;
        }
        #ctx_front {
          z-index: 5;
        }
        #ctx_back {
          z-index: 3;
        }
        #ctx_base {
          z-index: 1;
        }
        #text {
          position: absolute;
          z-index: -1;
          resize: none;
          outline: none;
          border: 1px dashed #eeeeee;
          overflow: hidden;
          background: transparent;
          line-height: 30px;
          display: none;
        }
      }
      .tools {
        width: 100%;
        position: absolute;
        display: flex;
        z-index: 5;
        background: #ffffff;
        transition: all 0.2s ease-in-out;
      }
      .settings {
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        z-index: 10;
        padding: 5px 10px;
        border-bottom-left-radius: 4px;
        border-bottom-right-radius: 4px;
        border: 1px solid #eeeeee;
        border-top: 0;
        width: auto;
        .tool_item {
          display: flex;
          align-items: center;
          flex-wrap: nowrap;
          &:not(:last-of-type) {
            margin-right: 25px;
          }
        }
        .go_up {
          margin-right: 0 !important;
        }
        button {
          display: flex;
          flex-wrap: nowrap;
          align-items: center;
          justify-content: center;
          padding: 5px 10px;
          background: #ffffff;
          border: 1px solid #eeeeee;
          outline: none;
          cursor: pointer;
          position: relative;
          flex-wrap: nowrap;
          svg {
            color: #333333;
            font-size: 18px;
            margin-right: 5px;
          }
          span {
            white-space: nowrap;
          }
          /deep/.el-color-picker {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            .el-color-picker__trigger {
              width: 100%;
              height: 100%;
              opacity: 0;
              filter: alpha(opacity=0);
            }
          }
        }
        .slide {
          width: 150px;
          display: flex;
          flex-direction: row;
          flex-wrap: nowrap;
          align-items: center;
          svg {
            font-size: 18px;
            margin-right: 5px;
          }
          /deep/.el-slider {
            flex: 1;
            width: 0;
            margin-left: 10px;
            .el-slider__button-wrapper {
              .el-slider__button {
                width: 12px;
                height: 12px;
              }
            }
          }
        }
        .pull {
          position: absolute;
          right: 20px;
          bottom: -45px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: flex-start;
          margin-right: 0;
          .line {
            width: 2px;
            height: 30px;
            background: dodgerblue;
          }
          .round {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background: dodgerblue;
            cursor: pointer;
          }
        }
      }
      .bars {
        top: 100px;
        right: 30px;
        z-index: 10;
        padding: 15px;
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
        border: 1px solid #eeeeee;
        width: auto;
        display: flex;
        flex-direction: column;
        .tool_item {
          cursor: pointer;
          &:not(:last-of-type) {
            margin-bottom: 15px;
            border-bottom: 1px solid #dddddd;
            padding-bottom: 10px;
          }
          svg {
            font-size: 24px;
            margin-right: 8px;
          }
          span {
            font-size: 18px;
          }
          &:hover {
            svg {
              color: dodgerblue;
            }
            span {
              color: dodgerblue;
            }
          }
        }
        .activeTool {
          border-color: dodgerblue !important;
          svg {
            color: dodgerblue;
          }
          span {
            color: dodgerblue;
          }
        }
        .arrow {
          width: 20px;
          height: 20px;
          text-align: center;
          line-height: 20px;
          border-radius: 50%;
          border: 1px solid #606266;
          color: #606266;
          position: absolute;
          left: -10px;
          background: #ffffff;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
        }
        .el-icon-s-tools {
          left: -30px;
          width: 30px;
          height: 30px;
          line-height: 30px;
          font-size: 20px;
          color: dodgerblue;
          border-color: dodgerblue;
        }
        .el-icon-arrow-right {
          left: calc(~"100% - 10px");
        }
      }
      .hideTools {
        right: -100px;
      }
      .noExpand {
        top: -50px;
      }
    }
  }
  .el-dialog__footer {
    text-align: center !important;
    span {
      button {
        padding-left: 40px;
        padding-right: 40px;
        &:first-of-type {
          margin-right: 50px;
        }
        &:last-of-type {
          margin-left: 50px;
        }
      }
    }
  }
}
</style>
